package com.research.demo.toolkit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class DBTool {
    private static DBHelper dbh;
    private static Logger log = LoggerFactory.getLogger(DBTool.class);

    static {
        String driver = ConfigTool.getByKey("MYSQL_DRIVER");
        String url = ConfigTool.getByKey("MYSQL_DB_URL_AF");
        String username = ConfigTool.getByKey("MYSQL_DB_USER");
        String password = ConfigTool.getByKey("MYSQL_DB_PASSWORD");
        String poolname = "antifraud";
        dbh = new DBHelper(driver, url, username, password, poolname);
    }

    public static int insert(String sql) {
        return execute(sql);
    }

    public static int insert(String sql, Object[] params) {
        return execute(sql, params);
    }

    public static int update(String sql) {
        return execute(sql);
    }

    public static int update(String sql, Object[] params) {
        return execute(sql, params);
    }

    public static int delete(String sql) {
        return execute(sql);
    }

    public static int delete(String sql, Object[] params) {
        return execute(sql, params);
    }

    public static int[] batch(String sql, Object[][] params) {
        int[] rowNum = null;

        try {
            rowNum = dbh.batch(sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rowNum;
    }

    public static List<Map<String, Object>> select(String sql) {
        List<Map<String, Object>> results = new ArrayList<>();
        try {
            results = dbh.query(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return results;
    }

    public static List<Map<String, Object>> select(String sql, Object[] params) {
        List<Map<String, Object>> results = new ArrayList<>();
        try {
            results = dbh.query(sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return results;
    }

    private static int execute(String sql) {
        int rowNum = 0;

        try {
            rowNum = dbh.execute(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rowNum;
    }


    private static int execute(String sql, Object[] params) {
        int rowNum = 0;

        try {
            rowNum = dbh.execute(sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rowNum;
    }
}
